package com.lsh.ofc.worker.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.entity.OfcObdHead;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.entity.OfcTask;
import com.lsh.ofc.core.enums.FulfillChannel;
import com.lsh.ofc.core.enums.OfcTaskStatus;
import com.lsh.ofc.core.enums.OfcTaskType;
import com.lsh.ofc.core.exception.EC;
import com.lsh.ofc.core.service.OfcObdService;
import com.lsh.ofc.core.service.OfcSoService;
import com.lsh.ofc.proxy.service.MisServiceProxy;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 创建SO任务
 *
 * @author peter
 * @date 19/4/25
 */
@Component
public class OfcObdMisBoxPushJob extends AbstractOfcTaskJob {

    @Autowired
    private OfcObdService ofcObdService;

    @Autowired
    private OfcSoService ofcSoService;

    @Autowired
    private MisServiceProxy misServiceProxy;

    @Override
    protected OfcTaskType getFetchTaskType() {
        return OfcTaskType.OBD_BOX_CONFERM_PUSH;
    }

    @Override
    protected int processTask(OfcTask task) throws BusinessException {

        try {
            String soBillCode = String.valueOf(task.getRefId());
            OfcObdHead filter = new OfcObdHead();
            filter.setSoBillCode(soBillCode);
            OfcObdHead obdHead = ofcObdService.findOne(filter, false);

            OfcSoHead soFilter = new OfcSoHead();
            soFilter.setSoBillCode(soBillCode);
            OfcSoHead soHead = ofcSoService.findOne(soFilter, false);

            if (null == obdHead || soHead == null) {
                return -1;
            }

            if (!FulfillChannel.SAAS_SC.getValue().equals(soHead.getFulfillChannel())) {
                throw EC.ERROR.exception("该订单不是云仓订单，FulfillChannel：" + soHead.getFulfillChannel());
            }

            String ext = obdHead.getExt();
            JSONObject obdExt = JSON.parseObject(ext);
            if (obdExt == null || obdExt.isEmpty()) {
                throw EC.ERROR.exception("该obd订单的ext信息为空");
            }

            boolean pushFlag = misServiceProxy.pushObdBoxInfo2mis(this.paramBuilder(obdHead.getOrderCode(), obdExt));

            if(pushFlag){
                return 1;
            }else{
                return -1;
            }
        } catch (BusinessException e) {
            logger.error("任务处理失败，任务信息：" + JSON.toJSONString(task), e);
            return -1;
        }
    }


    private List<BasicNameValuePair> paramBuilder(Long orderCode, JSONObject obdExt) {
        List<BasicNameValuePair> pairs = new ArrayList<>();

        String packageCodes = this.parseString(obdExt.getString("package_codes"));
        String scanPackageCodes = this.parseString(obdExt.getString("scan_package_codes"));
        String collectionLocation = this.parseString(obdExt.getString("collection_location"));

        pairs.add(new BasicNameValuePair("order_id", orderCode.toString()));

        if (StringUtils.isEmpty(collectionLocation)) {
            pairs.add(new BasicNameValuePair("package_way", collectionLocation));
        }

        List<String> packageCodeList = JSON.parseArray(packageCodes, String.class);
        if (!CollectionUtils.isEmpty(packageCodeList)) {
            pairs.add(new BasicNameValuePair("package_info", StringUtils.collectionToDelimitedString(packageCodeList, ",")));
            pairs.add(new BasicNameValuePair("package_num", packageCodeList.size() + ""));
        }

        List<String> scanPackageList = JSON.parseArray(scanPackageCodes, String.class);
        if (!CollectionUtils.isEmpty(scanPackageList)) {
            pairs.add(new BasicNameValuePair("scan_package_info", StringUtils.collectionToDelimitedString(scanPackageList, ",")));
            pairs.add(new BasicNameValuePair("scan_package_num", scanPackageList.size() + ""));
        }

        return pairs;
    }

    /**
     * @param param
     * @return
     */
    private String parseString(String param) {

        return StringUtils.isEmpty(param) == true ? "[]" : param;
    }


    @Override
    protected boolean filterFlag(OfcTask task) {
        return false;
    }

    @Override
    protected List<OfcTask> fetchTasks(OfcTaskType type, Set<OfcTaskStatus> statuses, int shardingCount, List<Integer> shardingItems, int fetchSize) {
        return super.defaultFetchTasks(type, statuses, shardingCount, shardingItems, fetchSize);
    }

}
